<template>
	<page-meta :page-style="'overflow:' + (show ? 'hidden' : 'visible')"></page-meta>
	<view class="container">
		<view class="gaps"></view>
		<template v-if="orderInfo.payState !== 2">
			<view class="order-con-panel ">
				<view class="order-pay-state">
					{{orderInfo.payState == 1? '订单完成':'支付成功'}}
				</view>
			</view>
			<view class="gaps"></view>
			<template v-if="orderInfo.addressId">
				<template v-if="orderInfo.addressId == 0">
					<view class="sq-panel">
						<view class="panel-tip">
							到店自提
						</view>
						<view class="panel-body">
							{{orderInfo.shopAddress}}
						</view>
					</view>
				</template>
				<template v-else>
					<view class="sq-panel">
						<view class="panel-tip">
							配送地址
						</view>
						<view class="panel-body">
							<view class="need-has-peisong">
								<view class="address">
									{{orderInfo.province + orderInfo.city  + orderInfo.district + orderInfo.address}}
								</view>
								<view class="contact">
									{{orderInfo.name}} {{orderInfo.phone}}
								</view>
							</view>
						</view>
					</view>

				</template>
				<view class="gaps"></view>
			</template>
		</template>
		<template v-else>
			<view class="order-con-panel ">
				<view class="wait-pay-panel">
					<view class="order-pay-state">
						待支付
					</view>
					<view class="wait-time">
						支付剩余
						<uni-countdown color="#000" :show-day="false" :show-colon="false" splitor-color="#000"
							:second="countdownSecond(orderInfo.createTime)" @timeup="onTimeOut" />
					</view>
				</view>
			</view>
			<view class="gaps"></view>

			<view class="order-con-panel peisong">
				<view class="tab-header">
					<view :class="peisongTab === 1 ? 'tab-active' : 'tab-no'" @click="addressTabChange(1)">到店自提</view>
					<view :class="peisongTab === 0 ? 'tab-active' : 'tab-no'" @click="addressTabChange(0)">同城配送</view>
				</view>
				<view class="peisong-content" v-show="peisongTab === 0" @click="needAddress">
					<template v-if="!orderInfo.address">
						<view class="need-peisong">
							<uni-icons type="location-filled" size="26"></uni-icons>
							<view>选择配送地址</view>
						</view>
						<view>
							<uni-icons type="forward" size="26" color="#b1b1b1"></uni-icons>
						</view>
					</template>
					<template v-else>
						<view class="need-has-peisong">
							<view class="address">
								{{orderInfo.province + orderInfo.city  + orderInfo.district + orderInfo.address}}
							</view>
							<view class="contact">
								{{orderInfo.name}} {{orderInfo.phone}}
							</view>
						</view>
						<view>
							<uni-icons type="forward" size="26" color="#b1b1b1"></uni-icons>
						</view>
					</template>
				</view>
				<view class="ziti-content" v-show="peisongTab === 1">
					店铺地址: <view class="shop-address">{{orderInfo.shopAddress || ""}}</view>
				</view>
			</view>
			<view class="gaps"></view>
		</template>

		<view class="sq-panel">
			<view class="panel-tip">
				订单内容
			</view>
			<view class="panel-body">
				<uni-list>
					<uni-list-item title="订单号" :right-text="orderInfo.id">
						<template slot="footer">
							{{orderInfo.id}}
						</template>
					</uni-list-item>
					<template v-if="orderInfo.deskName">
						<uni-list-item title="桌子号">
							<template slot="footer">
								{{orderInfo.deskName}}
							</template>
						</uni-list-item>
					</template>
					<template v-if="orderInfo.serialNum">
						<uni-list-item title="流水号"><template slot="footer">
								{{orderInfo.serialNum.toString().padStart(4, '0')}}
							</template>
						</uni-list-item>
					</template>
					<uni-list-item v-for="item in orderDetails" :key="item.id">
						<template v-slot:header>
							<view class="">
								<image :src="imageSrc(item.goodsPictures)" class="goods-img"></image>
							</view>
						</template>
						<template v-slot:body>
							<view class="goods-body">

								<view class="goods-intro">
									<view class="goods-name">{{item.goodsName}}</view>
									<view class="goods-price">
										{{priceTransform(item.buyPrice) + '/' + item.goodsSpec + ' X ' + item.goodsNum}}
									</view>
								</view>

							</view>
						</template>
						<template v-slot:footer>
							<view class="goods-sum-price">
								{{priceTransform(item.totalPrice)}}
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</view>
		<view class="gaps"></view>
		<view class="sq-panel">
			<view class="panel-tip">
				支付信息
			</view>
			<view class="panel-body">
				<uni-list>
					<uni-list-item title="订单金额">
						<template slot="footer">
							<view class="order-amount">
								{{priceTransform(orderInfo.orderMoney)}}
							</view>
						</template>
					</uni-list-item>
					<template v-if="orderInfo.payState == 2">
						<template v-if="orderInfo.wxOrderId">
							<uni-list-item title="优惠劵">
								<template slot="footer">
									<view class="order-amount">
										{{selCouponText()}}
									</view>
								</template>
							</uni-list-item>
						</template>
						<template v-else>
							<uni-list-item show-arrow clickable="true" @click="openCouponPop">
								<template slot="header">
									<view class="order-amount" style="color: red;font-size: 14px;">
										选择优惠券
									</view>
								</template>
								<template slot="footer">
									<view class="order-amount">
										{{selCouponText()}}
									</view>
								</template>
							</uni-list-item>
						</template>
						<uni-list-item title="可用积分">
							<template slot="footer">
								<view class="order-amount">
									{{priceTransform(walletYue / 100,2,'')}}
								</view>
							</template>
						</uni-list-item>
						<uni-list-item title="预计支付">
							<template slot="footer">
								<view class="order-amount">
									{{maybePay}}
								</view>
							</template>
						</uni-list-item>
					</template>
					<template v-else>
						<uni-list-item title="优惠劵">
							<template slot="footer">
								<view class="order-amount">
									{{selCouponText()}}
								</view>
							</template>
						</uni-list-item>
						<uni-list-item title="使用积分">
							<template slot="footer">
								<view class="order-amount">
									{{priceTransform(walletYue / 100,2,'')}}
								</view>
							</template>
						</uni-list-item>
						<uni-list-item title="实际支付">
							<template slot="footer">
								<view class="order-amount">
									{{priceTransform(orderInfo.realPayMoney)}}
								</view>
							</template>
						</uni-list-item>
					</template>
				</uni-list>
			</view>
		</view>

		<view class="gaps"></view>
		<template v-if="orderInfo.payState !== 2">
			<template v-if="orderInfo.remark">
				<view class="order-con-panel remark">
					<view class="remark-tip">
						备注
					</view>
					<view class="remark-info">
						{{orderInfo.remark || '没有备注'}}
					</view>
				</view>
				<view class="gaps"></view>
			</template>
		</template>
		<template v-else>
			<view class="sq-panel">
				<view class="panel-tip">
					备注
				</view>
				<uni-easyinput auto-height type="textarea" maxlength="200" placeholder="备注信息(200字以内)"
					v-model="orderInfo.remark"></uni-easyinput>
				<view class="remark-btn">
					<view>
						<u-button type="success" @click="editRemarkClk" text="保存">保存</u-button>
					</view>
				</view>
			</view>
			<view class="gaps"></view>
		</template>
		<view class="sq-panel">
			<view class="panel-tip">店铺信息</view>
			<view class="panel-body">
				<uni-list :border="false">
					<uni-list-item :title="orderInfo.shopName"
						:note="orderInfo.openTime ? (orderInfo.openTime + ' 至 ' + orderInfo.closeTime) : ''"
						:thumb="orderInfo.logoUrl" thumb-size="lg">
						<template v-slot:header>
							<view class="">
								<image :src="imageSrc(orderInfo.logoUrl)" class="goods-img"></image>
							</view>
						</template>
						<template v-slot:body>
							<view class="goods-body">

								<view class="goods-intro">
									<view class="goods-name">{{orderInfo.shopName}}</view>
									<view class="goods-price">
										{{orderInfo.openTime ? (orderInfo.openTime + ' 至 ' + orderInfo.closeTime) : ''}}
									</view>
								</view>

							</view>
						</template>
						<template v-slot:footer>
							<view class="goods-sum-price" style="min-width: 60px;">
								返 {{orderInfo.fxzk}}%
							</view>
						</template>

					</uni-list-item>
				</uni-list>
			</view>
		</view>
		<view class="gaps" :style="{height:(safeBottom + 60) + 'px'}"></view>
		<template v-if="orderInfo.payState == 2">
			<view class="order-opre" :style="{paddingBottom:safeBottom + 'px'}">
				<u-button text="支付" @click="payNow" type="success"></u-button>
			</view>
		</template>
		<uni-popup ref="couponPop" type="bottom" :mask-click="false" :safeArea="false">
			<view class="goods-detail-pop" style="background-color: #fff; border-radius: 10px 10px 0 0; padding-top: 10px;"
				:style="{ height: `${windowHeight - statusBarHeight - navigationBarHeight - 100}px` }">
				<view class="pop-header">
					<view class="sel-order-num">请选择优惠券</view>
					<uni-icons type="closeempty" color="#c8c8c8" size="25" @click="closeCouponPop"></uni-icons>
				</view>
				<view class="pop-body">
					<template v-if="coupons.length">
					<scroll-view scroll-y="true" :scroll-top="scorllTop"
						:style="{ height: `${windowHeight - statusBarHeight - navigationBarHeight - 100 - 40 - safeBottom}px` }">
						<view class="card" v-for="item in coupons" :key="item.id" @click="selectCoupon(item)">
							<view class="card-left">{{priceTransform(item.price,2,'')}}<text class="card-unit">元</text></view>
							<view class="card-right">
								<view class="card-info">抵扣券</view>
								<strong class="card-time">{{formatDateTime(item.expirationTime)}} 后过期</strong>
							</view>
						</view>
					</scroll-view>
					</template>
					<template v-else>
						<u-empty
						        mode="coupon"
						>
						</u-empty>
					</template>
				</view>
			</view>
		</uni-popup>
		
	</view>

	
</template>

<script>
	import {
		getOrderInfo,
		payOrder,
		getWxpayStatus,
		completePay,
		bindAddress,
		unBindAddress,
		editRemark,
		orderTimeout,
		getMyCoupon,
		getCouponByOrderId
	} from '@/api/consomer/orderDetail/orderDetail.js'
	import {
		getMyAddressById,
	} from '@/api/consomer/receiveAddressManage/receiveAddressManage.js'
	import {
		getMyWallet,
	} from '@/api/my/my'
	import {
		transform,
		systemInfo
	} from '@/minix/mixin.js'
	export default {
		mixins: [systemInfo, transform],
		data() {
			return {
				orderInfo: {
					id: '',
					shopId: '',
					fxzk: 0,
					orderMoney: 0,
					createTime: 0,
				},
				orderDetails: [],
				safeBottom: 0,
				peisongTab: 1,
				addressTabs: [{
					title: '同城配送'
				}, {
					title: '到店自提'
				}],
				coupons:[],
				selCoupon:{},
				walletYue:0,
				maybePay:0,
				show:false
				
			}
		},

		onLoad: function(option) {
			this.getSystemInfo()
			this.orderInfo.id = option.id
			this.init()
		},
		methods: {
			init() {
				uni.getSystemInfo({
					success: (res) => {
						this.safeBottom = res.screenHeight - res.safeArea.bottom
					}
				})
				let pre1 =  getOrderInfo(this.orderInfo.id)
				
				let pre2 = getMyWallet()
				
				let pre3 = getCouponByOrderId(this.orderInfo.id)
				
				let _this =this
				Promise.all([pre1,pre2,pre3]).then((results) => {
					let res = results[0]
					_this.shopInfo = res.shopVo
					_this.orderDetails = res.orderDetailVos
					delete res.shopVo
					delete res.orderDetailVos
					_this.orderInfo = res
					if (res.addressId == 0) {
						_this.peisongTab = 1;
					}

					_this.walletYue = results[1].backMoney;
					
					_this.selCoupon = results[2]
					
					_this.calPay()
				})
			},
			calPay() {
				let r = this.orderInfo.orderMoney - this.walletYue - (this.selCoupon?.price || 0)
				if(r < 0) {
					r = 0
				}
				this.maybePay = this.priceTransform(r);
			},
			selCouponText() {
				if(this.selCoupon?.price) {
					return '优惠' + this.priceTransform(this.selCoupon.price,2,'') + '元'
				}
				return ''
			},
			
			openCouponPop() {
				getMyCoupon(this.orderInfo.shopId).then((res) => {
					this.coupons = res
					this.$refs.couponPop.open()
					this.show = true
				})
			},
			selectCoupon(coupon) {
				this.selCoupon = coupon
				this.calPay()
				this.closeCouponPop()
			},
			
			closeCouponPop() {
				this.$refs.couponPop.close()
				this.show = false
			},
			paySuccessGotoOrder() {
				uni.showToast({
					icon: 'none',
					title: '支付成功'
				})
				setTimeout(() => {
					getApp().globalData.newOrder = "true";
					uni.switchTab({
						url: '/pages/myOrder/myOrder'
					})
				}, 400)
			},
			countdownSecond(creatTime) {
				let t = creatTime + (30 * 60 * 1000) - Date.now()
				t = t / 1000
				return t
			},
			onTimeOut() {
				orderTimeout(this.orderInfo.id)
				uni.showModal({
					showCancel: false,
					content: '订单支付超时',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack()
						}
					}
				})
			},
			async payNow() {
				if (this.peisongTab === 0 && !this.orderInfo.address) {
					return uni.showModal({
						title: '请选择配送地址或选择到店自提',
						showCancel: false
					})
				}
				if (this.peisongTab === 1) {
					await bindAddress({
						orderId: this.orderInfo.id,
						addressId: 0
					})
				}
				const _this = this
				let res = await payOrder({
					orderId: this.orderInfo.id,
					couponId : _this.selCoupon?.id || ''
				})
				if (res.noNeedPay) {
					const payModal = await uni.showModal({
						title: '提示',
						content: '钱包余额充足,需实际支付0元',
						confirmText: '支付',
					})
					if (payModal[1].confirm) {
						uni.showLoading({
							title: '支付中',
							mask: true
						})

						completePay({
							orderId: this.orderInfo.id
						}).then(() => {
							_this.orderInfo.payState = 3
							_this.paySuccessGotoOrder()
						}).catch((e) => {
							uni.showToast({
								icon: 'error',
								title: e.data.msg
							})
						}).finally(() => {
							uni.hideLoading()
						})

					}
				} else {
					let _this = this
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.timeStamp,
						nonceStr: res.nonceStr,
						package: res.packages,
						signType: res.signType,
						paySign: res.paySign,
						complete: async function(e) {
							let ps = await getWxpayStatus({
								orderId: _this.orderInfo.id
							})
							if (ps.payState === 0) {
								_this.orderPayState = 0
								_this.orderOpre = true
								await completePay({
									orderId: _this.orderInfo.id
								})
								_this.paySuccessGotoOrder()
								return
							} else {
								uni.showModal({
									title: '提示',
									content: ps.payStateDesc,
									showCancel: false,
								})
							}
						}
					})
				}
			},
			needAddress() {
				const _this = this
				uni.navigateTo({
					url: '/subpkg/consumer/receiveAddressManage/receiveAddressManage',
					events: {
						selAddr(data) {
							if (data.id) {
								getMyAddressById(data.id).then((rs) => {
									rs.addressId = rs.id
									delete rs.id
									_this.orderInfo = Object.assign({}, _this.orderInfo, rs)
									if (rs.addressId) {
										bindAddress({
											orderId: _this.orderInfo.id,
											addressId: rs.addressId
										})
									}
								})
							}
						}
					}
				})
			},
			addressTabChange(index) {
				if (this.peisongTab !== index) {
					this.peisongTab = index;
				}
			},
			editRemarkClk() {
				editRemark({
					orderId: this.orderInfo.id,
					remark: this.orderInfo.remark || ''
				}).then(() => {
					uni.showToast({
						icon: 'none',
						title: '保存成功'
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
		padding-bottom: 60px;
	}

	.order-pay-state {
		background-color: #fff;
		color: red;
		text-align: center;
		width: 100%;
		font-size: 16px;
		font-weight: 600;
	}


	.wait-pay-panel {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;

		.wait-time {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 100%;
		}
	}

	.order-con-panel {
		width: 95%;
		background-color: #fff;
		display: flex;
		flex-direction: row;
		padding: 10px;
		border-radius: 10px;
		margin: 0 auto;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 0 2px 1px #ccc;

		&.peisong {
			flex-direction: column;
		}


	}

	.tab-header {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		font-size: 18px;
		height: 40px;
		line-height: 40px;
		text-align: center;

	}

	.tab-active {
		flex: 1;
		color: $base-color;
		font-weight: bold;
		border-top: 1px solid #ccc;
		border-left: 1px solid #ccc;
		border-right: 1px solid #ccc;
		border-radius: 10px 10px 0 0;
	}

	.tab-no {
		flex: 1;
		border-bottom: 1px solid #ccc;
		background-color: #ccc;
		border-radius: 10px 10px 0 0;
		color: #a29c9c;
		font-size: 16px;
	}

	.peisong-content {
		display: flex;
		justify-content: space-between;
		width: 100%;
		margin-top: 10px;
		align-items: center;
	}

	.ziti-content {
		width: 100%;
		margin-top: 10px;
		font-size: 16px;
	}

	.need-peisong {
		display: flex;
		flex-direction: row;
		align-items: center;
		font-size: 16px;
	}

	.peisong-area {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.need-has-peisong {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;

		.address {
			font-size: 16px;
			font-weight: 600;
		}

		.contact {
			font-size: 16px;
			margin-top: 5px;
		}
	}

	.shop-address {
		font-weight: bold;
		display: inline;
	}

	.remark-btn {
		width: 100%;
		margin-top: 5px;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
	}

	.remark-info {
		width: 100%;
		padding: 0 20px;
	}

	.order-opre {
		display: flex;
		flex-direction: row;
		justify-content: flex-end;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 10;
		background-color: #fff;
		button {
			width: 100%;
		}
	}

	.no-need-peisong {
		margin-right: 10px;
		height: 30px;
		font-size: 15px;
		color: $base-color;
		display: flex;
		justify-content: flex-end;
		align-items: flex-end;
		text-decoration: underline;
	}

	.goods-img {
		width: 60px;
		height: 60px;
		border-radius: 5px;
	}

	.goods-body {
		margin-left: 8px;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.goods-intro {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-name {
		font-size: 16px;
		font-weight: bold;
	}

	.goods-price {
		font-size: 14px;
	}

	.goods-sum-price {
		display: flex;
		align-items: center;
	}
	
	.pop-header{
		display: flex;
		justify-content: space-between;
		padding: 0 10px;
	}

	.card {
		display: flex;
		align-items: center;
		background: #fef0ef;
		border-radius: 8px;
		-webkit-mask-image: radial-gradient(circle at 88px 4px, transparent 4px, red 4.5px), radial-gradient(closest-side circle at 50%, red 99%, transparent 100%);
		-webkit-mask-size: 100%, 2px 4px;
		-webkit-mask-repeat: repeat, repeat-y;
		-webkit-mask-position: 0 -4px, 87px;
		-webkit-mask-composite: source-out;
		mask-composite: subtract;
		width: 85%;
		margin: 0 auto;
		margin-top: 8px;
	}

	.card-left {
		width: 88px;
		text-align: center;
		font-size: 24px;
		color: #fe3a31;
		.card-unit{
			font-size: 12px;
		}
	}

	.card-left span {
		font-size: 10px;
	}

	.card-right {
		padding: 16px 12px;
		display: flex;
		flex: 1;
		flex-direction: column;
		.card-info {
			margin: 0;
			font-size: 14px;
			font-weight: bold;
			line-height: 20px;
			color: rgba(33, 32, 44, 0.9);
		}
		.card-time {
			font-size: 12px;
			line-height: 16px;
			font-weight: normal;
			color: #a9a09f;
			margin-top: 4px;
		}
	}

	

	
</style>